Page({
  data: {
    username: '',
    password: ''
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  handleLogin() {
    const { username, password } = this.data;
    
    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      });
      return;
    }

    let loadingShown = false;
    try {
      wx.showLoading({
        title: '登录中...',
      });
      loadingShown = true;

      wx.request({
        url: 'http://localhost:8080/api/user/login',
        method: 'POST',
        data: {
          username,
          password
        },
        success: (res) => {
          if (res.data.code === 1) {
            // 存储用户信息
            const userInfo = res.data.data;
            wx.setStorageSync('userInfo', userInfo);
            
            // 确保token是字符串类型，并去除可能的空白字符
            const token = String(userInfo.token).trim();
            console.log('Token:', token); // 添加日志
            wx.setStorageSync('token', token);
            
            // 设置全局用户信息
            const app = getApp();
            app.globalData.userInfo = userInfo;
            
            // 初始化WebSocket连接
            app.initWebSocket(token);
            
            wx.showToast({
              title: '登录成功',
              icon: 'success'
            });
            
            // 登录成功后跳转到首页
            wx.switchTab({
              url: '/pages/index/index'
            });
          } else {
            wx.showToast({
              title: res.data.msg || '登录失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('登录请求失败:', err);
          wx.showToast({
            title: '网络错误，请检查网络设置',
            icon: 'none'
          });
        },
        complete: () => {
          if (loadingShown) {
            wx.hideLoading();
          }
        }
      });
    } catch (error) {
      console.error('登录过程出错:', error);
      if (loadingShown) {
        wx.hideLoading();
      }
      wx.showToast({
        title: '系统错误，请重试',
        icon: 'none'
      });
    }
  }
}); 